﻿using System;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using MusicAlarm7.DataModel;
using MusicAlarm7.Resources;

namespace TileUpdateAgent
{
    public sealed class AppTile
    {
        private const string taskName = "MusicAlarmTask";

        public static void Update()
        {
            ShellTile tile = ShellTile.ActiveTiles.First();
            StandardTileData data = new StandardTileData();
            TimeSpan eta = TimeSpan.MaxValue;

            foreach (AlarmItem a in ViewModel.Alarms)
            {
                if (a.Eta < eta) eta = a.Eta;
            }

            if (eta < TimeSpan.MaxValue)
            {
                RelativeTimeConverter conv = new RelativeTimeConverter();
                data.Title = AppResources.Tile_NextAlarm + conv.Convert(DateTime.Now + eta, typeof(string), null, System.Globalization.CultureInfo.CurrentCulture).ToString();

                tile.Update(data);
            }
        }

        public static void SetSchedule()
        {
            PeriodicTask t;

            // Obtain a reference to the period task, if one exists
            t = ScheduledActionService.Find(taskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (t != null)
            {
                RemoveAgent(taskName);
            }

            t = new PeriodicTask(taskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            t.Description = AppResources.Task_Description;

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(t);

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if DEBUG
                ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(60));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show(AppResources.Task_Disabled);
                }
                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.
                }
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }
        }

        private static void RemoveAgent(string name)
        {
            try
            {
                ScheduledActionService.Remove(name);
            }
            catch (Exception)
            {
            }
        }


        private static AlarmViewModel _viewmodel = null;
        public static AlarmViewModel ViewModel
        {
            get
            {
                if (_viewmodel == null)
                {
                    _viewmodel = new AlarmViewModel();
                    _viewmodel.LoadFromDatabase();
                }
                return _viewmodel;
            }
        }
    }
}
